<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="发票抬头" prop="invoiceTitle">
        <el-input
          v-model="queryParams.invoiceTitle"
          placeholder="请输入发票抬头"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="公司名称" prop="company">
        <el-input
          v-model="queryParams.company"
          placeholder="请输入公司名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="购方税号" prop="taxNumber">
        <el-input
          v-model="queryParams.taxNumber"
          placeholder="请输入购方税号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input
          v-model="queryParams.contactPhone"
          placeholder="请输入联系电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系邮箱" prop="contactEmail">
        <el-input
          v-model="queryParams.contactEmail"
          placeholder="请输入联系邮箱"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">


      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:requests:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:requests:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="requestsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="发票申请ID" align="center" prop="id" />
      <el-table-column label="开票责任公司" align="center" prop="company" />
      <el-table-column label="发票抬头" align="center" prop="invoiceTitle" />
      
      <el-table-column label="纳税人识别号" align="center" prop="taxNumber" />
      <el-table-column label="发票类型" align="center" prop="invoiceType">
        <template slot-scope="scope">
          <span>{{ scope.row.invoiceType === 1 ? '个人' : '企业' }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="联系电话" align="center" prop="contactPhone" />
      <el-table-column label="联系邮箱" align="center" prop="contactEmail" /> -->
      <el-table-column label="开票金额(元)" align="center" prop="amount" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <span v-if="scope.row.status === 0">待处理</span>
          <span v-if="scope.row.status === 1">处理中</span>
          <span v-if="scope.row.status === 2">已完成</span>
          <span v-if="scope.row.status === 3">已取消</span>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" align="center" prop="createTime" width="180">

      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-upload2"
            @click="handleProcess(scope.row)"
            v-hasPermi="['system:requests:edit']"
            v-if="scope.row.status === 0"
          >处理</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-close"
            @click="handleCancel(scope.row)"
            v-hasPermi="['system:requests:edit']"
            v-if="scope.row.status === 0"
          >取消</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:requests:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改发票申请对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 处理发票申请对话框 -->
    <el-dialog :title="'处理发票申请'" :visible.sync="processOpen" width="500px" append-to-body>
      <el-form ref="processForm" :model="processForm" :rules="processRules" label-width="100px">
        <el-form-item label="发票文件" prop="fileUrl">
          <el-upload
            class="upload-pdf"
            :http-request="customUpload"
            :show-file-list="false"
            accept=".pdf"
            :before-upload="beforeUpload"
          >
            <div v-if="processForm.fileUrl" class="file-name">
              <i class="el-icon-document"></i>
              <span>{{ processForm.fileUrl }}</span>
            </div>
            <el-button v-else type="primary">选择文件</el-button>
            <div class="el-upload__tip" slot="tip">请上传PDF格式的发票文件，且文件大小不超过10MB</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitProcess">确 定</el-button>
        <el-button @click="cancelProcess">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog :title="'发票申请详情'" :visible.sync="detailOpen" width="600px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="开票责任公司">{{ detailForm.company }}</el-descriptions-item>
        <el-descriptions-item label="发票申请ID">{{ detailForm.id }}</el-descriptions-item>
        <el-descriptions-item label="发票抬头">{{ detailForm.invoiceTitle }}</el-descriptions-item>
        
        <el-descriptions-item label="纳税人识别号">{{ detailForm.taxNumber }}</el-descriptions-item>
        <el-descriptions-item label="发票类型">{{ detailForm.invoiceType === 1 ? '个人' : '企业' }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ detailForm.contactPhone }}</el-descriptions-item>
        <el-descriptions-item label="联系邮箱">{{ detailForm.contactEmail }}</el-descriptions-item>
        <el-descriptions-item label="开票金额">{{ detailForm.amount }} 元</el-descriptions-item>
        <el-descriptions-item label="状态">
          <span v-if="detailForm.status === 0">待处理</span>
          <span v-if="detailForm.status === 1">处理中</span>
          <span v-if="detailForm.status === 2">已完成</span>
          <span v-if="detailForm.status === 3">已取消</span>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailForm.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detailForm.updateTime }}</el-descriptions-item>
        <el-descriptions-item label="发票文件" v-if="detailForm.fileUrl">
          <el-link type="primary" :href="detailForm.fileUrl" target="_blank">查看发票</el-link>
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detailForm.remark || '-' }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRequests, getRequests, delRequests, addRequests, updateRequests } from "@/api/system/requests";
import { getToken } from "@/utils/auth";
import { uploadToCOS } from "@/api/passenger/upload";

export default {
  name: "Requests",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 发票申请表格数据
      requestsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        invoiceTitle: null,
        company: null,
        taxNumber: null,
        invoiceType: null,
        contactPhone: null,
        contactEmail: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        invoiceTitle: [
          { required: true, message: "发票抬头不能为空", trigger: "blur" }
        ],
        invoiceType: [
          { required: true, message: "发票类型：1-个人，2-企业不能为空", trigger: "change" }
        ],
        amount: [
          { required: true, message: "开票金额(元)不能为空", trigger: "blur" }
        ],
      },
      // 是否显示处理对话框
      processOpen: false,
      // 处理表单参数
      processForm: {
        id: null,
        fileUrl: null,
        status: 2
      },
      // 处理表单校验
      processRules: {
        fileUrl: [
          { required: true, message: "请上传发票文件", trigger: "change" }
        ]
      },
      // 上传文件列表
      fileList: [],
      // 上传地址
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      // 上传头部
      headers: {
        Authorization: "Bearer " + getToken()
      },
      // 是否显示详情对话框
      detailOpen: false,
      // 详情表单
      detailForm: {},
      // 基础路径
      baseUrl: 'https://suzhou-taxi-1306862033.cos.ap-chengdu.myqcloud.com/file/',
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询发票申请列表 */
    getList() {
      this.loading = true;
      listRequests(this.queryParams).then(response => {
        this.requestsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        tripIds: null,
        invoiceTitle: null,
        company: null,
        taxNumber: null,
        invoiceType: null,
        contactPhone: null,
        contactEmail: null,
        amount: null,
        status: null,
        fileUrl: null,
        fileName: null,
        fileSize: null,
        remark: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加发票申请";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRequests(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改发票申请";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRequests(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRequests(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除发票申请编号为"' + ids + '"的数据项？').then(function() {
        return delRequests(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/requests/export', {
        ...this.queryParams
      }, `requests_${new Date().getTime()}.xlsx`)
    },
    /** 处理按钮操作 */
    handleProcess(row) {
      this.resetProcess();
      this.processForm.id = row.id;
      this.processOpen = true;
    },
    // 重置处理表单
    resetProcess() {
      this.processForm = {
        id: null,
        fileUrl: null,
        status: 2
      };
    },
    // 取消处理
    cancelProcess() {
      this.processOpen = false;
      this.resetProcess();
    },
    // 上传前校验
    beforeUpload(file) {
      const isPDF = file.type === 'application/pdf';
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isPDF) {
        this.$message.error('只能上传PDF文件!');
        return false;
      }
      if (!isLt10M) {
        this.$message.error('文件大小不能超过 10MB!');
        return false;
      }
      return true;
    },
    // 自定义上传方法
    customUpload(event) {
      let file = event.file;
      if(file.size/1024 > 10*1024){
        this.$message.warning('单个文件大小不能超过10MB');
        return;
      }
      let data = new FormData();
      data.append('file', file);
      this.$modal.loading("正在上传文件，请稍候...");
      uploadToCOS(data).then(response => {
        this.$modal.closeLoading();
        if (response.code === 200) {
          this.processForm.fileUrl = response.data;
          this.$modal.msgSuccess("上传成功");
        } else {
          this.$modal.msgError("上传失败");
        }
      }).catch(() => {
        this.$modal.closeLoading();
        this.$modal.msgError("上传失败");
      });
    },
    // 提交处理
    submitProcess() {
      this.$refs["processForm"].validate(valid => {
        if (valid) {
          updateRequests(this.processForm).then(response => {
            this.$modal.msgSuccess("处理成功");
            this.processOpen = false;
            this.getList();
          });
        }
      });
    },
    /** 取消按钮操作 */
    handleCancel(row) {
      this.$modal.confirm('是否确认取消该发票申请？').then(() => {
        const cancelForm = {
          id: row.id,
          status: 3
        };
        updateRequests(cancelForm).then(response => {
          this.$modal.msgSuccess("取消成功");
          this.getList();
        });
      }).catch(() => {});
    },
    /** 查看详情按钮操作 */
    handleDetail(row) {
      this.detailForm = { ...row };
      // 如果文件路径不是以http开头，则添加基础路径
      if (this.detailForm.fileUrl) {
        this.detailForm.fileUrl = this.baseUrl + this.detailForm.fileUrl;

      }
      this.detailOpen = true;
    }
  }
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.upload-pdf {
  text-align: center;
}
.upload-pdf .file-name {
  line-height: 32px;
  display: inline-flex;
  align-items: center;
}
.upload-pdf .file-name i {
  margin-right: 5px;
  font-size: 20px;
}
</style>
